package top.soeasy.wechat.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import top.soeasy.common.constant.Constants;
import top.soeasy.common.core.domain.entity.SysMember;
import top.soeasy.common.core.redis.RedisCache;
import top.soeasy.framework.security.token.MobileCodeAuthenticationToken;
import top.soeasy.common.utils.StringUtils;
import top.soeasy.wechat.mapper.SysMemberMapper;
import top.soeasy.wechat.service.ISysMemberService;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SysMemberServiceImpl implements ISysMemberService {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysMemberMapper memberMapper;

    @Override
    public String sendPhoneCode(String phone) {
        String codeKey = Constants.PHONE_CODE_KEY + phone;

        String code = redisCache.getCacheObject(codeKey);
        if (StringUtils.isNotEmpty(code)) {
            return code;
        } else {
            StringBuilder sb = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < 6; i++) {
                sb.append(random.nextInt(10));
            }

            redisCache.setCacheObject(codeKey, sb, Constants.PHONE_CODE_EXPIRATION, TimeUnit.MINUTES);
            return sb.toString();
        }
    }

    @Override
    public SysMember findMemberByMobile(String mobile) {
        return memberMapper.findMemberByMobile(mobile);
    }

}
